<?php

namespace App\Service\Auth;

use App\Cache\RedisKey;
use App\Constants\ErrorCode;
use App\Event\InviteEvent;
use App\Event\RegDoneEvent;
use App\Helpers\Helper;
use App\Helpers\RedisUtil;
use App\Model\Guild\GuildHost;
use App\Model\Guild\GuildManage;
use App\Model\ProfileVerifyLog;
use App\Model\Setting\SettingAppHidden;
use App\Model\User;
use App\Model\UserActLog;
use App\Model\UserAvatarLog;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;
use App\Service\BaseService;
use Psr\EventDispatcher\EventDispatcherInterface;

/**
 * 完善资料
 */
class FixProfileService extends BaseService
{
    protected function RoVerifyList()
    {
        return [
            'nick_name' => "required|string",
            'birthday' => "required|string",
            'gender' => "required|int",
            // 'avatar' => "required|string",
            'invite_code' => "|string"
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        $nickName = $this->request->input('nick_name');
        $birthday = $this->request->input('birthday');
        $gender = $this->request->input('gender', -1);
        $inviteCode = $this->request->input('invite_code', '');
        $avatar = $this->request->input('avatar', '');

        $city = $this->request->input('locate_city', '');
        if (Helper::checkLocationRegLimited($city)) {
            return ['errcode' => ErrorCode::USER_NOT_VALID, 'errmsg' => "暂时不允许注册平台～"];
        }

        $realAvatar = $avatar ?: ($gender == 1 ? UserProfile::pickAvatar(1) : 'default/fe_avatar.jpeg');
        $info = [
            'user_id' => $userId,
            'user_profile_id' => UserProfile::makeProfileUid($userId),
            'nick_name' => $nickName,
            'gender' => $gender,
            'birthday' => $birthday,
            'avatar' => $realAvatar,
            'poster' => '',
        ];

        //处理邀请码
        $this->proccessInviteCode($info, $inviteCode);

        //添加或更新用户信息
        if($gender == 0){
            $info['coin_setting'] = 20;
            $info['video_coin_setting'] = 40;
            $info['chat_coin_setting'] = 2;
        }
        $result = UserProfile::updateOrCreate(['user_id' => $userId], $info);

        // 检查是否屏蔽推送，加入屏蔽集合
        if ($gender == 1 && $this->curVersion  && $this->curChannel && $this->appId) {
            $checkHidden = SettingAppHidden::checkModuleHiddenByUser($userId, $this->appId, $this->curVersion, $this->curChannel, SettingAppHidden::FUNC_PUSH);
            if ($checkHidden == 1) {
                $redis = RedisUtil::getRedis();

                $key = RedisKey::appHiddenUser();

                $redis->sAdd($key, $userId);

                log_info(__CLASS__.'==放入屏蔽set==userId:'.$userId);
            }
        }

        $ret['result'] = $result ? 1 : 0;
        $user = $this->getUser();
        $ret['user_info'] = $this->packBaseUserInfo($user);

        //修改融云账号资料
        $result = User::updateIMInfo($user->im_account, $ret['user_info']['nick_name'], $ret['user_info']['avatar']);

        //邀请回调
        if ($inviteCode && $profile = UserProfile::getInfoByProfileId($inviteCode)) {
            make(EventDispatcherInterface::class)->dispatch(new InviteEvent($profile->user_id, $userId, $profile));
        }

        //头像注册
        if ($avatar) UserAvatarLog::addRecord($userId, $avatar);

        //审核记录
        ProfileVerifyLog::addRecord($userId, ProfileVerifyLog::TYPE_NICKNAME, $nickName);

        //注册完成事件
        make(EventDispatcherInterface::class)->dispatch(new RegDoneEvent($userId, $gender));
        log_user_result($userId, $ret);
        return $ret;
    }

    /**
     * 邀请码
     */
    function proccessInviteCode(&$info = [], $inviteCode = '')
    {
        if (!$inviteCode) return;
        //绑定邀请码
        if (UserProfile::isProfileIdValid($inviteCode)) $info['invite_code'] = $inviteCode;
        //公会主播，清空被邀请关系
        if (GuildHost::checkInGuild($info['user_id'])) $info['invite_code'] = '';
        //公会绑定ID
        elseif ($guildInfo = GuildManage::getInfoByGuildId($inviteCode)) {
            // $guildInfo = GuildManage::getInfoByGuildId($inviteCode);
            $vrf = UserProfilePersonal::isRealnameVerified(UserProfilePersonal::getProfile($inviteCode));
            GuildHost::bindHost($info['user_id'], $guildInfo['id'], $vrf, $info['user_profile_id']);
            $info['invite_code'] = '';
        }
        return;
    }
}
